import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/prescription.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';

/// @Author lixiaobin
/// @Date 2024/2/20
/// @Description 处方单预览
class PrescriptionPreViewPage extends StatefulWidget {
  final String prescriptionNo;

  const PrescriptionPreViewPage({super.key, required this.prescriptionNo});

  @override
  State<PrescriptionPreViewPage> createState() => _PrescriptionPreViewPageState();
}

class _PrescriptionPreViewPageState extends State<PrescriptionPreViewPage> {
  Prescription? _prescription;
  bool _isLoad = false;

  @override
  void initState() {
    super.initState();
    _getPrescription();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: CommWidget.getCommAppbar(context),
        body: Container(
            color: ColorRes.colorf9f9fa,
            child: _isLoad
                ? Stack(children: [_loadPrescriptionImg(), _getStatusImg()])
                : CommWidget.buildEmptyView(tipStr: '加载中')));
  }

  /// 加载处方单图片
  Widget _loadPrescriptionImg() {
    return ImageLoader.loadImage(_prescription?.prescriptionImg ?? '',
        size: const Size(double.infinity, double.infinity),
        fit: BoxFit.fill,
        errorWidget: CommWidget.buildEmptyView(tipStr: '服务器打盹了，请稍后再试！'));
  }

  /// 加载处方单状态图片
  Widget _getStatusImg() {
    String? image;
    if (_prescription?.expried == true) {
      image = 'icon_prescription_status_1.webp';
    } else if (_prescription?.isOrder == '0' || _prescription?.isOrder == '1') {
      image = 'icon_prescription_status_2.webp';
    } else if (_prescription?.isOrder == '2') {
      image = 'icon_prescription_status_3.webp';
    }
    return Container(
      alignment: Alignment.topRight,
      margin: EdgeInsets.only(top: 10.w),
      child: (StringUtils.isEmpty(image) || StringUtils.isEmpty(_prescription?.prescriptionImg))
          ? null
          : ImageLoader.loadAsset(image ?? '', 70.w),
    );
  }

  /// 获取处方单
  _getPrescription() async {
    var response = await HttpClient.postJson(
        HttpRequest(Api.findPrescriptionByPrescriptionNo, urlParams: {'prescriptionNo': widget.prescriptionNo}));
    var serviceResult = ServiceResult<Prescription>(response, (map) => Prescription.fromJson(map));
    if (serviceResult.success) {
      _prescription = serviceResult.responseBody;
      setState(() {});
    }
    _isLoad = true;
  }
}
